package dbTest;

import com.alibaba.fastjson2.JSON
import enums.Country
import kotlinx.html.S
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.noear.solon.Solon
import test.t1.IpLocationInfo
import test.t1.MmdbReader
import java.io.File
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.CopyOption
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.UUID

@Serializable
data class Region(
    val code: String,
    val name: String,
    var children: MutableList<Region> = mutableListOf()
)

val url = "https://api.ipinfo.io/lite/38.147.171.207?token=ddfb3f71a09ef8"

fun main() {
    println(UUID.randomUUID().toString())

    Files.copy(Path.of("E:\\数据\\1&2区8.28-9.2注册用户信息.xlsx"), Path.of("C:\\Windows"), StandardCopyOption.REPLACE_EXISTING)

    /*val client = HttpClient.newHttpClient()

    val request = HttpRequest.newBuilder()
        .uri(URI.create(url)).GET()
        .build()
    val response = client.send(request, HttpResponse.BodyHandlers.ofString())
    println(response.body())

    val locationInfo = JSON.parseObject(response.body(), IpLocationInfo::class.java)

//    println(JSON.toJSONString(locationInfo))

    println(Country.entries.size)

    regions.forEach {
        val country = Country.ofZhName(it.name)
        if(country == null) {
//            println("未获取到 ${it.name}")
        }
    }

    readmmDb()*/
}

val regions = Json.decodeFromString<List<Region>>(File("region.json").readText())

fun readmmDb() {
    val dbPath = "./ipinfo_lite.mmdb"
    val ipInfo = MmdbReader()

    try {
        ipInfo.init(dbPath)

        val ip = "3.5.143.201"

        println("IP: $ip")
        val lookup = ipInfo.lookup(ip)
        println("完整数据: ${JSON.toJSONString(lookup)}")

        val country = Country.of(lookup["country_code"].toString())
        println("国家: $country")

    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
    }
}
fun t1() {
    /*val mySQLBenchmark = MySQLBenchmark()
    var connection = mySQLBenchmark.getConnection()

    val regions = mutableListOf<Region>()

    connection.use {
        val preparedStatement = it.prepareStatement("""
            select * from sys_lang s
            INNER JOIN d_area d on s.vc_code = d.vc_area_name AND d.l_level = 0
            where s.e_lang_type = 'zh_CN'
        """.trimIndent())
        preparedStatement.use { it1 ->
            val resultSet = it1.executeQuery()
            resultSet.use { it ->
                while (it.next()) {
                    regions.add(Region(
                        code = it.getString("vc_code"),
                        name = it.getString("vc_name"),
                    ))
                }
            }
        }
    }


    regions.forEach { region ->
        connection = mySQLBenchmark.getConnection()
        connection.use {
            val preparedStatement = it.prepareStatement("""
            select * from sys_lang s
            INNER JOIN d_area d on d.vc_area_name = s.vc_code AND d.l_level = 1
            where s.e_lang_type = 'zh_CN'
            and d.vc_area_name LIKE '${region.code}%'
        """.trimIndent())
            preparedStatement.use { it1 ->
                val resultSet = it1.executeQuery()
                resultSet.use { rs ->
                    while (rs.next()) {
                        region.children.add(Region(
                            code = rs.getString("vc_code"),
                            name = rs.getString("vc_name"),
                        ))
                    }
                }
            }
        }
    }

    val string = Json.encodeToString(regions)
    File("region.json").writeText(string)*/


    val urlList = Json.decodeFromString<TurnUrlList>(File("inner.json").readText())
    val regionGroupList = Json.decodeFromString<RegionGroupList>(File("region-group.json").readText())
    regionGroupList.groups.forEach {
        val addRs = mutableListOf<String>()
        it.regions.forEach { it1 ->
            if(it1.startsWith("@")) {
                val group = regionGroupList.groups.find { it2 -> it2.name == it1 }
                addRs.addAll(group!!.regions)

            }
        }
        it.regions.addAll(addRs)
        it.regions.removeIf { it1 -> it1.startsWith("@") }
    }

    urlList.urls.forEach {
        it.regions.forEach { it1 ->
            val addRs = mutableListOf<String>()
            it1.region.forEach { it2 ->
                if(it2.startsWith("@")) {
                    val group = regionGroupList.groups.find { it3 -> it3.name == it2 }
                    addRs.addAll(group!!.regions)
                }
            }
            it1.region.addAll(addRs)
            it1.region.removeIf { it2 -> it2.startsWith("@") }
        }
    }

    println(Json.encodeToString(urlList))
    val src = "中国"
    val tar = "中国"
    val src1 = "香港"
    val tar1 = "江苏"
    val okList = mutableListOf<String>()
    for (turnUrl in urlList.urls) {
        val b = turnUrl.country.contains(src)
        val b2 = turnUrl.country.contains(tar)
        // 国家必须满足
        if(!b || !b2) continue
        // 对此国家地区进行精准的切分
        turnUrl.regions.forEach {
            val b1 = it.region.contains(src1)
            val b3 = it.region.contains(tar1)
            if(b1 && b3) {
                okList.add(it.url)
            }
        }
        // 国家级别的地址保底没匹配上使用
        if(okList.isEmpty()) okList.add(turnUrl.url)
    }
    println("符合的有：${Json.encodeToString(okList)}")

    regions.forEach {
        if(it.name == "中国") {
            val toList = it.children.map { it.name }.toList()
            println("中国：${Json.encodeToString(toList)}")
        }
    }
}

@Serializable
data class TurnUrlList(
    val desc: String,
    val urls: MutableList<TurnUrl>,
    var default: String
)

@Serializable
data class TurnUrl(
    var desc: String = "",
    val url: String,
    val country: String,
    val regions: MutableList<Region1>,
)

@Serializable
data class Region1(
    var desc: String = "",
    val url: String,
    val region: MutableList<String>
)

@Serializable
data class RegionGroupList(
    val groups: MutableList<RegionGroup>,
)
@Serializable
data class RegionGroup(
    val name: String,
    val regions: MutableList<String>
)